import { PROJ_CFG_KEY } from '@/enums/cacheEnum';
import projectSetting from '@/settings/projectSetting';
import { deepMerge } from '@/utils';
import { Persistent } from '@/utils/cache/persistent';
import { getCommonStoragePrefix, getStorageShortName } from '@/utils/env';
import { ProjectConfig } from '~/config';
import { useAppStore } from '@/store/modules/app';
import { ThemeEnum } from '@/enums/appEnum';
import { updateHeaderBgColor, updateSidebarBgColor } from './updateBackground';

export function initAppConfigStore() {
	const appStore = useAppStore();
	let projCfg: ProjectConfig = Persistent.getLocal(PROJ_CFG_KEY) as ProjectConfig;
	projCfg = deepMerge(projectSetting, projCfg || {});
	appStore.setDarkMode(ThemeEnum.LIGHT);

	const { headerSetting: { bgColor: headerBgColor } = {}, menuSetting: { bgColor } = {} } = projCfg;

	// TODO: 动态修改主题颜色、头部颜色、菜单颜色;
	appStore.setProjectConfig(projCfg);

	if (appStore.getDarkMode === ThemeEnum.DARK) {
		updateHeaderBgColor();
		updateSidebarBgColor();
	} else {
		headerBgColor && updateHeaderBgColor(headerBgColor);
		bgColor && updateSidebarBgColor(bgColor);
	}

	setTimeout(() => {
		clearObsoleteStorage();
	}, 16);
}

// 删除和当前版本号不一致的缓存
export function clearObsoleteStorage() {
	const commonPrefix = getCommonStoragePrefix();
	const shortPrefix = getStorageShortName();

	[localStorage, sessionStorage].forEach((item: Storage) => {
		Object.keys(item).forEach(key => {
			if (key && key.startsWith(commonPrefix) && !key.startsWith(shortPrefix)) {
				item.removeItem(key);
			}
		});
	});
}
